package com.dszq.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dszq.common.exception.CustomException;
import com.dszq.model.common.dtos.PageResponseResult;
import com.dszq.model.common.dtos.ResponseResult;
import com.dszq.model.common.enums.AppHttpCodeEnum;
import com.dszq.model.wemedia.dtos.WmMaterialDto;
import com.dszq.model.wemedia.pojos.WmMaterial;
import com.dszq.model.wemedia.pojos.WmNews;
import com.dszq.model.wemedia.pojos.WmNewsMaterial;
import com.dszq.utils.thread.WmThreadLocalUtil;
import com.dszq.wemedia.mapper.WmMaterialMapper;
import com.dszq.wemedia.mapper.WmNewsMaterialMapper;
import com.dszq.wemedia.service.WmMaterialService;
import com.dszq.file.service.FileStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * [一句话描述该类的功能]
 *
 * @author : [Lenovo]
 * @version : [v1.0]
 * @createTime : [2024/4/17 22:04]
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    /**
     * 图片上传
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //1.检查参数
        if(multipartFile==null||multipartFile.getSize()==0)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.上传图片到minIO中
        String fileName = UUID.randomUUID().toString().replace("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileId = null;
        try {
            fileId = fileStorageService.uploadImgFile("", fileName + postfix, multipartFile.getInputStream());
            log.info("上传图片到minIO中，fileId:{}",fileId);
        }catch (Exception e)
        {
            e.printStackTrace();
            log.info("上传图片到minIO中失败，fileName:{},e:{}",fileName,e);
        }
        //3.保存到数据库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setUrl(fileId);
        wmMaterial.setIsCollection((short)0);
        wmMaterial.setType((short)0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 查询图片列表
     *
     * @param wmMaterialDto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {
        //检查参数
        wmMaterialDto.checkParam();
        //分页查询
        IPage page = new Page(wmMaterialDto.getPage(),wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        //条件：是否收藏
        if (wmMaterialDto.getIsCollection()!=null&&wmMaterialDto.getIsCollection()==1)
        {
            queryWrapper.eq(WmMaterial::getIsCollection,wmMaterialDto.getIsCollection());
        }
        //条件：用户id
        queryWrapper.eq(WmMaterial::getUserId, WmThreadLocalUtil.getUser().getId());
        //按照时间
        queryWrapper.orderByDesc(WmMaterial::getCreatedTime);

        page = page(page,queryWrapper);

        ResponseResult responseResult = new PageResponseResult(wmMaterialDto.getPage(),wmMaterialDto.getSize(),(int)page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 根据ID删除素材
     *
     * @param id 要删除的素材的ID，不能为空。
     * @return ResponseResult 返回操作的结果，其中包含成功与否、错误码和错误信息等。
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deleteById(Integer id) {
        // 检查ID是否为空
        if (id == null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 检查记录是否存在
        if (wmMaterialMapper.selectById(id)==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 删除记录
        List<Integer> newsId = wmNewsMaterialMapper.selectByWmMaterialId(id);
        int key = wmMaterialMapper.deleteById(id);

        // 根据删除结果返回相应信息
        if (key ==1&&newsId.size()==0)
        {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文件删除失败,有文章使用了该素材");
        }
    }

    /**
     * 修改指定ID的素材为收藏或取消收藏
     *
     * @param id 收藏的唯一标识符，指定要修改的素材的ID
     * @return ResponseResult 返回一个结果对象，包含操作是否成功及相应信息。如果操作成功，返回成功的状态码和消息；如果操作失败，返回失败的状态码和错误消息。
     */
    @Override
    public ResponseResult collectionOrCancel(Integer id) {
        // 检查ID是否为空
        if (id == null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID); // 参数无效，返回错误结果
        }
        WmMaterial wmMaterial = wmMaterialMapper.selectById(id);
        // 检查记录是否存在
        if (wmMaterial==null)
        {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST); // 数据不存在，返回错误结果
        }
        // 切换收藏状态
        if (wmMaterial.getIsCollection()==0)
        {
            wmMaterial.setIsCollection((short) 1); // 当前未收藏，修改为收藏状态
        }else {
            wmMaterial.setIsCollection((short) 0); // 当前已收藏，修改为取消收藏状态
        }
        wmMaterialMapper.updateById(wmMaterial); // 更新数据库中的收藏状态
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS); // 操作成功，返回成功结果
    }

}
